<template>
  <view class="portrait-camera-container">
    <!-- 顶部导航栏 -->
    <view class="camera-header">
      <view class="header-left">
        <button class="cancel-button" @click="handleCancel">
          <uni-icons type="back" size="24" color="#ffffff"></uni-icons>
        </button>
      </view>
      <view class="header-center">
        <text class="camera-title">{{ title || "拍摄照片" }}</text>
      </view>
      <view class="header-right"></view>
    </view>

    <!-- 相机预览区域 -->
    <view class="camera-preview">
      <!-- #ifdef APP-PLUS || MP-WEIXIN -->
      <camera
        v-if="cameraReady"
        ref="cameraRef"
        class="camera-view"
        device-position="front"
        flash="off"
        @error="handleCameraError"
        @initdone="handleCameraInit"
      >
        <!-- 人像引导遮罩层 -->
        <view class="portrait-guide-overlay">
          <!-- 引导框 -->
          <view class="guide-frame">
            <!-- 人像轮廓 使用CSS边框 -->
            <view class="portrait-outline">
              <!-- 人像轮廓图片 -->
              <image
                src="/static/headborder.png"
                class="person-outline-image"
                mode="aspectFit"
              ></image>
            </view>
          </view>

          <!-- 引导文字 -->
          <view class="guide-text">
            <text class="guide-main-text">{{
              guideText || "请将人像对准引导框"
            }}</text>
            <text class="guide-sub-text">确保光线充足，人像清晰可见</text>
          </view>
        </view>
      </camera>
      <!-- #endif -->

      <!-- #ifdef H5 -->
      <!-- H5端使用背景图和引导 -->
      <view class="h5-camera-placeholder">
        <view class="portrait-guide-overlay">
          <view class="guide-frame">
            <view class="portrait-outline">
              <!-- 人像轮廓图片 -->
              <image
                src="/static/headborder.png"
                class="person-outline-image"
                mode="aspectFit"
              ></image>
            </view>
          </view>
          <view class="guide-text">
            <text class="guide-main-text">H5端请选择相册中的照片</text>
            <text class="guide-sub-text">或在移动端使用拍照功能</text>
          </view>
        </view>
      </view>
      <!-- #endif -->
    </view>

    <!-- 底部操作区域 -->
    <view class="camera-controls">
      <!-- 左侧空白区域 -->
      <view class="control-left"> </view>

      <!-- 拍照按钮 -->
      <view class="control-center">
        <!-- #ifdef APP-PLUS || MP-WEIXIN -->
        <button
          v-if="cameraReady"
          class="capture-button"
          @click="handleCapture"
          :disabled="capturing"
        >
          <view class="capture-inner" :class="{ capturing: capturing }"></view>
        </button>
        <!-- #endif -->

        <!-- #ifdef H5 -->
        <button
          class="capture-button h5-capture"
          @click="handleChooseFromAlbum"
        >
          <uni-icons type="image" size="32" color="#ffffff"></uni-icons>
        </button>
        <!-- #endif -->
      </view>

      <!-- 相册选择 -->
      <view class="control-right">
        <button class="album-button" @click="handleChooseFromAlbum">
          <uni-icons type="image" size="28" color="#ffffff"></uni-icons>
        </button>
      </view>
    </view>

    <!-- 加载提示 -->
    <view v-if="capturing" class="loading-overlay">
      <view class="loading-content">
        <uni-icons type="spinner-cycle" size="32" color="#ffffff"></uni-icons>
        <text class="loading-text">正在处理...</text>
      </view>
    </view>

    <!-- 权限提示 -->
    <view v-if="showPermissionTip" class="permission-overlay">
      <view class="permission-content">
        <uni-icons type="camera" size="48" color="#7881de"></uni-icons>
        <text class="permission-title">需要相机权限</text>
        <text class="permission-desc">请允许访问相机以使用拍照功能</text>
        <button class="permission-button" @click="requestPermission">
          重新授权
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

// Props
interface Props {
  title?: string;
  guideText?: string;
  maxSize?: number; // 最大文件大小(MB)
  quality?: number; // 图片质量 0-1
}

const props = withDefaults(defineProps<Props>(), {
  title: "拍摄照片",
  guideText: "请将人像对准引导框",
  maxSize: 5,
  quality: 0.8,
});

// Emits
const emit = defineEmits<{
  success: [file: { path: string; size: number }];
  cancel: [];
  error: [error: any];
}>();

// 响应式数据
const cameraReady = ref(false);
const showPermissionTip = ref(false);
const capturing = ref(false);
const cameraRef = ref<any>(null);

// 相机初始化完成
const handleCameraInit = () => {
  console.log("相机初始化完成");
  cameraReady.value = true;
  showPermissionTip.value = false;
};

// 相机错误处理
const handleCameraError = (error: any) => {
  console.error("相机错误:", error);
  cameraReady.value = false;
  showPermissionTip.value = true;

  // 在App端和小程序端显示权限提示，H5端直接使用相册
  // #ifdef H5
  handleChooseFromAlbum();
  // #endif

  // #ifndef H5
  uni.showToast({
    title: "相机启动失败",
    icon: "none",
  });
  // #endif

  emit("error", error);
};

// 拍照处理
const handleCapture = () => {
  if (capturing.value) return;

  capturing.value = true;

  // 创建相机上下文
  const ctx = uni.createCameraContext();

  ctx.takePhoto({
    quality:
      props.quality === 1 ? "high" : props.quality > 0.5 ? "normal" : "low",
    success: (res) => {
      console.log("拍照成功:", res);

      // 检查文件大小
      uni.getFileInfo({
        filePath: res.tempImagePath,
        success: (fileInfo) => {
          const fileSizeMB = fileInfo.size / (1024 * 1024);

          if (fileSizeMB > props.maxSize) {
            uni.showToast({
              title: `图片大小不能超过${props.maxSize}MB`,
              icon: "none",
            });
            capturing.value = false;
            return;
          }

          // 返回成功结果
          emit("success", {
            path: res.tempImagePath,
            size: fileInfo.size,
          });

          capturing.value = false;
        },
        fail: (error) => {
          console.error("获取文件信息失败:", error);
          emit("error", error);
          capturing.value = false;
        },
      });
    },
    fail: (error) => {
      console.error("拍照失败:", error);
      uni.showToast({
        title: "拍照失败",
        icon: "none",
      });
      emit("error", error);
      capturing.value = false;
    },
  });
};

// 从相册选择
const handleChooseFromAlbum = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album"],
    success: (res) => {
      const filePath = res.tempFilePaths[0];

      // 检查文件大小
      uni.getFileInfo({
        filePath,
        success: (fileInfo) => {
          const fileSizeMB = fileInfo.size / (1024 * 1024);

          if (fileSizeMB > props.maxSize) {
            uni.showToast({
              title: `图片大小不能超过${props.maxSize}MB`,
              icon: "none",
            });
            return;
          }

          // 返回成功结果
          emit("success", {
            path: filePath,
            size: fileInfo.size,
          });
        },
        fail: (error) => {
          console.error("获取文件信息失败:", error);
          emit("error", error);
        },
      });
    },
    fail: (error) => {
      console.error("选择图片失败:", error);
      emit("error", error);
    },
  });
};

// 权限请求
const requestPermission = () => {
  // #ifdef APP-PLUS
  uni.authorize({
    scope: "scope.camera",
    success: () => {
      console.log("相机权限授权成功");
      showPermissionTip.value = false;
      cameraReady.value = true;
    },
    fail: () => {
      uni.showModal({
        title: "需要相机权限",
        content: "请在设置中开启相机权限以使用拍照功能",
        confirmText: "去设置",
        success: (res) => {
          if (res.confirm) {
            uni.openSetting();
          }
        },
      });
    },
  });
  // #endif

  // #ifdef MP-WEIXIN
  uni.authorize({
    scope: "scope.camera",
    success: () => {
      console.log("相机权限授权成功");
      showPermissionTip.value = false;
      cameraReady.value = true;
    },
    fail: () => {
      uni.showModal({
        title: "需要相机权限",
        content: "请在小程序设置中开启相机权限",
        confirmText: "确定",
        success: () => {
          handleChooseFromAlbum();
        },
      });
    },
  });
  // #endif

  // #ifdef H5
  handleChooseFromAlbum();
  // #endif
};

// 取消拍照
const handleCancel = () => {
  emit("cancel");
};

// 暴露方法
defineExpose({
  requestPermission,
});

// 生命周期
onMounted(() => {
  // 初始化相机权限检查
  // #ifdef H5
  // H5端直接显示选择图片的界面
  cameraReady.value = false;
  showPermissionTip.value = false;
  // #endif

  // #ifndef H5
  // App端和小程序端请求相机权限
  setTimeout(() => {
    requestPermission();
  }, 500);
  // #endif
});

onUnmounted(() => {
  // 清理资源
  cameraReady.value = false;
  showPermissionTip.value = false;
});
</script>

<style lang="scss" scoped>
.portrait-camera-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: #000000;
  display: flex;
  flex-direction: column;
}

.camera-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10rpx);
  position: relative;
  z-index: 10;

  // 添加安全区域适配
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
  height: calc(88rpx + constant(safe-area-inset-top));
  height: calc(88rpx + env(safe-area-inset-top));

  .header-left,
  .header-right {
    width: 80rpx;
  }

  .header-center {
    flex: 1;
    text-align: center;
  }

  .cancel-button {
    background: none;
    border: none;
    padding: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      border: none;
    }
  }

  .camera-title {
    color: #ffffff;
    font-size: 36rpx;
    font-weight: 500;
  }
}

.camera-preview {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.camera-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.portrait-guide-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  z-index: 10;
  background: rgba(0, 0, 0, 0.3);
}

.guide-frame {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 80rpx 60rpx;
  width: 100%;
}

.portrait-outline {
  width: 75%;
  height: 75%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 人像轮廓图片样式
.person-outline-image {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
}

// 动画效果
@keyframes outline-glow {
  0% {
    border-color: rgba(255, 255, 255, 0.7);
    box-shadow:
      0 0 20rpx rgba(255, 255, 255, 0.3),
      inset 0 0 20rpx rgba(255, 255, 255, 0.05);
  }
  100% {
    border-color: rgba(255, 255, 255, 1);
    box-shadow:
      0 0 40rpx rgba(255, 255, 255, 0.6),
      inset 0 0 30rpx rgba(255, 255, 255, 0.1);
  }
}

@keyframes line-pulse {
  0% {
    opacity: 0.4;
  }
  100% {
    opacity: 0.8;
  }
}

.guide-text {
  position: absolute;
  bottom: 50rpx;
  left: 0;
  right: 0;
  text-align: center;
  padding: 0 60rpx;
}

.guide-main-text {
  display: block;
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 500;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.5);
}

.guide-sub-text {
  display: block;
  color: rgba(255, 255, 255, 0.8);
  font-size: 22rpx;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.5);
}

.camera-controls {
  height: 200rpx;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10rpx);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 60rpx;
  position: relative;
  z-index: 10;

  // 添加安全区域适配
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  height: calc(200rpx + constant(safe-area-inset-bottom));
  height: calc(200rpx + env(safe-area-inset-bottom));
}

.control-left,
.control-right {
  width: 80rpx;
  display: flex;
  justify-content: center;
}

.control-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.album-button {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);

  &::after {
    border: none;
  }

  &:active {
    background: rgba(255, 255, 255, 0.3);
  }
}

.capture-button {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  border: 4rpx solid #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);

  &::after {
    border: none;
  }

  &:active {
    transform: scale(0.95);
  }

  &[disabled] {
    opacity: 0.6;
  }
}

.capture-inner {
  width: 80rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #ffffff;
  transition: all 0.2s ease;

  &.capturing {
    animation: capture-animation 0.5s ease;
  }
}

@keyframes capture-animation {
  0% {
    transform: scale(1);
    background: #ffffff;
  }
  50% {
    transform: scale(0.8);
    background: #ff4757;
  }
  100% {
    transform: scale(1);
    background: #ffffff;
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.loading-text {
  color: #ffffff;
  font-size: 28rpx;
}

// H5端相机占位符
.h5-camera-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

// 权限提示覆盖层
.permission-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.permission-content {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  max-width: 600rpx;
  margin: 0 40rpx;

  .permission-title {
    display: block;
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
    margin: 32rpx 0 16rpx 0;
  }

  .permission-desc {
    display: block;
    font-size: 28rpx;
    color: #666666;
    line-height: 1.5;
    margin-bottom: 40rpx;
  }

  .permission-button {
    background: #7881de;
    color: #ffffff;
    border: none;
    border-radius: 8rpx;
    padding: 24rpx 48rpx;
    font-size: 32rpx;
    font-weight: 500;

    &::after {
      border: none;
    }

    &:active {
      background: #6670d1;
      transform: scale(0.98);
    }
  }
}

// H5端拍照按钮特殊样式
.h5-capture {
  .capture-inner {
    display: none;
  }
}

// 响应式适配
@media (max-width: 768rpx) {
  .person-outline-image {
    width: 100%;
    height: 100%;
  }

  .guide-text {
    bottom: 180rpx;
  }

  .guide-main-text {
    font-size: 28rpx;
  }

  .guide-sub-text {
    font-size: 24rpx;
  }

  .permission-content {
    margin: 0 20rpx;
    padding: 40rpx 30rpx;

    .permission-title {
      font-size: 32rpx;
    }

    .permission-desc {
      font-size: 26rpx;
    }

    .permission-button {
      padding: 20rpx 40rpx;
      font-size: 28rpx;
    }
  }
}
</style>
